import { onMounted, onUnmounted, ref } from "vue";
import { throttle } from "underscore";

export default function reachBottomListener(elRef) {
  let el = window;

  const isReachBottom = ref(false);
  const clientHeight = ref(0);
  const scrollTop = ref(0);
  const scrollHeight = ref(0);

  const reachBottomHandler = throttle(() => {
    // clientHeight.value = document.documentElement.clientHeight;
    // scrollTop.value = document.documentElement.scrollTop;
    // scrollHeight.value = document.documentElement.scrollHeight;
    if (el === window) {
      scrollTop.value = document.documentElement.scrollTop;
      scrollHeight.value = document.documentElement.scrollHeight;
      //客户端页面的高度
      clientHeight.value = document.documentElement.clientHeight;
    } else {
      scrollTop.value = el.scrollTop;

      scrollHeight.value = el.scrollHeight;
      //客户端页面的高度
      clientHeight.value = el.clientHeight;
    }
    if (clientHeight.value + scrollTop.value >= scrollHeight.value) {
      isReachBottom.value = true;
    }
  }, 100);

  onMounted(() => {
    // window.addEventListener("scroll", reachBottomHandler);
    if (elRef) el = elRef.value;

    el.addEventListener("scroll", reachBottomHandler);
  });
  onUnmounted(() => {
    // window.removeEventListener("scroll", reachBottomHandler);
    el.removeEventListener("scroll", reachBottomHandler);
  });

  return {
    isReachBottom,
    clientHeight,
    scrollTop,
    scrollHeight,
  };
}
